// 本地存储工具类

import type { FilterState, EnvironmentType } from '@/types';

const STORAGE_KEYS = {
  FILTER_STATE: 'env_manager_filter_state',
  ACTIVE_ENVIRONMENTS: 'env_manager_active_environments',
  ACTIVE_ENVIRONMENT_TYPE: 'env_manager_active_environment_type', // 新增：记录当前激活的环境类型
  PROJECT_ACTIVE_ENV: 'env_manager_project_active_env', // 新增：记录每个项目当前激活的环境
};

export class StorageManager {
  private static instance: StorageManager;

  private constructor() {}

  public static getInstance(): StorageManager {
    if (!StorageManager.instance) {
      StorageManager.instance = new StorageManager();
    }
    return StorageManager.instance;
  }

  // 保存筛选状态
  public saveFilterState(filterState: FilterState): void {
    try {
      localStorage.setItem(STORAGE_KEYS.FILTER_STATE, JSON.stringify(filterState));
    } catch (error) {
      console.error('保存筛选状态失败:', error);
    }
  }

  // 获取筛选状态
  public getFilterState(): FilterState {
    try {
      const data = localStorage.getItem(STORAGE_KEYS.FILTER_STATE);
      if (data) {
        return JSON.parse(data);
      }
    } catch (error) {
      console.error('获取筛选状态失败:', error);
    }
    
    // 返回默认状态
    return {
      searchKeyword: '',
      selectedGroupIds: [],
    };
  }

  // 获取项目活跃环境映射
  private getProjectActiveEnvMap(): Record<string, string> {
    try {
      const data = localStorage.getItem(STORAGE_KEYS.PROJECT_ACTIVE_ENV);
      if (data) {
        return JSON.parse(data);
      }
    } catch (error) {
      console.error('获取项目活跃环境映射失败:', error);
    }
    return {};
  }

  // 保存项目活跃环境映射
  private saveProjectActiveEnvMap(projectEnvMap: Record<string, string>): void {
    try {
      localStorage.setItem(STORAGE_KEYS.PROJECT_ACTIVE_ENV, JSON.stringify(projectEnvMap));
    } catch (error) {
      console.error('保存项目活跃环境映射失败:', error);
    }
  }

  // 获取环境所属的项目ID
  private getProjectIdByEnvironmentId(envId: string, allProjects: Array<{id: string, environments: Array<{id: string}>}>): string | null {
    for (const project of allProjects) {
      if (project.environments.some(env => env.id === envId)) {
        return project.id;
      }
    }
    return null;
  }

  // 添加活跃环境状态（智能互斥激活 + 项目级别限制）
  public addActiveEnvironments(id: string, envType: EnvironmentType, allProjects: Array<{id: string, environments: Array<{id: string, type: EnvironmentType}>}>): void {
    const currentActive = this.getActiveEnvironments();
    const projectEnvMap = this.getProjectActiveEnvMap();
    
    // 获取环境所属的项目ID
    const projectId = this.getProjectIdByEnvironmentId(id, allProjects);
    if (!projectId) {
      console.error('无法找到环境所属的项目:', id);
      return;
    }

    if (envType === 'custom') {
      // 自定义环境：直接添加到活跃列表，不受互斥限制
      if (!currentActive.includes(id)) {
        currentActive.push(id);
        // 更新项目活跃环境映射
        projectEnvMap[projectId] = id;
      }
    } else {
      // 标准环境：清除同一项目下的其他环境，保留其他项目的环境
      
      // 从当前活跃列表中移除同一项目的其他环境
      const filteredActive = currentActive.filter(activeId => {
        const activeProjectId = this.getProjectIdByEnvironmentId(activeId, allProjects);
        return activeProjectId !== projectId; // 保留其他项目的环境
      });
      
      // 2. 添加新的环境
      filteredActive.push(id);
      currentActive.length = 0;
      currentActive.push(...filteredActive);
      
      // 3. 更新项目活跃环境映射
      projectEnvMap[projectId] = id;
      
      // 4. 记录当前激活的标准环境类型
      localStorage.setItem(STORAGE_KEYS.ACTIVE_ENVIRONMENT_TYPE, envType);
    }
    
    try {
      localStorage.setItem(STORAGE_KEYS.ACTIVE_ENVIRONMENTS, JSON.stringify(currentActive));
      this.saveProjectActiveEnvMap(projectEnvMap);
    } catch (error) {
      console.error('保存活跃环境状态失败:', error);
    }
  }

  // 重载方法：添加活跃环境状态（传入完整环境信息）
  public addActiveEnvironmentsWithInfo(id: string, envType: EnvironmentType, projectId: string): void {
    const currentActive = this.getActiveEnvironments();
    const projectEnvMap = this.getProjectActiveEnvMap();
    
    if (envType === 'custom') {
      // 自定义环境：直接添加到活跃列表，不受互斥限制
      if (!currentActive.includes(id)) {
        currentActive.push(id);
        // 更新项目活跃环境映射
        projectEnvMap[projectId] = id;
      }
    } else {
      // 标准环境：清除同一项目下的其他环境，保留其他项目的环境
      

      // 1. 获取当前项目的活跃环境
      const currentProjectActiveEnv = projectEnvMap[projectId];
      
      // 2. 如果当前项目有活跃环境，从活跃列表中移除
      if (currentProjectActiveEnv && currentProjectActiveEnv !== id) {
        const index = currentActive.indexOf(currentProjectActiveEnv);
        if (index > -1) {
          currentActive.splice(index, 1);
        }
      }
      
      // 3. 添加新的环境（如果还没有激活的话）
      if (!currentActive.includes(id)) {
        currentActive.push(id);
      }
      
      // 4. 更新项目活跃环境映射
      projectEnvMap[projectId] = id;
      
      // 5. 记录当前激活的标准环境类型
      localStorage.setItem(STORAGE_KEYS.ACTIVE_ENVIRONMENT_TYPE, envType);
    }
    
    try {
      localStorage.setItem(STORAGE_KEYS.ACTIVE_ENVIRONMENTS, JSON.stringify(currentActive));
      this.saveProjectActiveEnvMap(projectEnvMap);
    } catch (error) {
      console.error('保存活跃环境状态失败:', error);
    }
  }
  
  // 删除活跃环境状态
  public deleteActiveEnvironments(id: string, allProjects: Array<{id: string, environments: Array<{id: string}>}>): void {
    const data = this.getActiveEnvironments();
    const projectEnvMap = this.getProjectActiveEnvMap();
    
    const index = data.indexOf(id);
    if (index > -1) {
      data.splice(index, 1);
      
      // 更新项目活跃环境映射
      const projectId = this.getProjectIdByEnvironmentId(id, allProjects);
      if (projectId && projectEnvMap[projectId] === id) {
        delete projectEnvMap[projectId];
      }
      
      try {
        localStorage.setItem(STORAGE_KEYS.ACTIVE_ENVIRONMENTS, JSON.stringify(data));
        this.saveProjectActiveEnvMap(projectEnvMap);
        
        // 如果没有活跃环境，清除环境类型记录
        if (data.length === 0) {
          localStorage.removeItem(STORAGE_KEYS.ACTIVE_ENVIRONMENT_TYPE);
        }
      } catch (error) {
        console.error('删除活跃环境状态失败:', error);
      }
    }
  }

  // 获取活跃环境状态
  public getActiveEnvironments(): string[] {
    try {
      const data = localStorage.getItem(STORAGE_KEYS.ACTIVE_ENVIRONMENTS);
      if (data) {
        return JSON.parse(data);
      }
    } catch (error) {
      console.error('获取活跃环境状态失败:', error);
    }
    
    return [];
  }

  // 获取当前激活的环境类型
  public getActiveEnvironmentType(): EnvironmentType | null {
    try {
      const data = localStorage.getItem(STORAGE_KEYS.ACTIVE_ENVIRONMENT_TYPE);
      if (data) {
        return data as EnvironmentType;
      }
    } catch (error) {
      console.error('获取活跃环境类型失败:', error);
    }
    
    return null;
  }

  // 获取项目的活跃环境ID
  public getProjectActiveEnvironment(projectId: string): string | null {
    const projectEnvMap = this.getProjectActiveEnvMap();
    return projectEnvMap[projectId] || null;
  }

  // 检查项目是否已有活跃环境
  public isProjectHasActiveEnvironment(projectId: string): boolean {
    return this.getProjectActiveEnvironment(projectId) !== null;
  }

  // 清除所有活跃环境
  public clearAllActiveEnvironments(): void {
    try {
      localStorage.removeItem(STORAGE_KEYS.ACTIVE_ENVIRONMENTS);
      localStorage.removeItem(STORAGE_KEYS.ACTIVE_ENVIRONMENT_TYPE);
      localStorage.removeItem(STORAGE_KEYS.PROJECT_ACTIVE_ENV);
    } catch (error) {
      console.error('清除活跃环境状态失败:', error);
    }
  }

  // 检查环境是否应该被激活（基于互斥逻辑）
  public shouldActivateEnvironment(envType: EnvironmentType): boolean {
    const currentActiveType = this.getActiveEnvironmentType();
    // 如果没有激活的环境，或者当前环境类型与要激活的类型不同，则可以激活
    return !currentActiveType || currentActiveType !== envType;
  }

  // 清除所有存储数据
  public clearAll(): void {
    try {
      localStorage.removeItem(STORAGE_KEYS.FILTER_STATE);
      localStorage.removeItem(STORAGE_KEYS.ACTIVE_ENVIRONMENTS);
      localStorage.removeItem(STORAGE_KEYS.ACTIVE_ENVIRONMENT_TYPE);
      localStorage.removeItem(STORAGE_KEYS.PROJECT_ACTIVE_ENV);
    } catch (error) {
      console.error('清除存储数据失败:', error);
    }
  }
}

// 导出单例实例
export const storageManager = StorageManager.getInstance();
